package ca.jsbr.as2js_lib.event 
{
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.utils.Dictionary;
	import js.window;
	/**
	 * ...
	 * @author jsbr [me@jsbr.ca]
	 */
	public class EventDispatcher implements IEventDispatcher 
	{
		private var _event:Dictionary;
		
		public function EventDispatcher() 
		{
			_event = new Dictionary();
		}
		
		
		
		public function addEventListener(evtType:String, listener:Function):void 
		{		
			if (!_event[evtType]) {
				_event[evtType] = [];
			}
			//if(findEvent(evtType, listener)==-1)
			_event[evtType].push(listener);
			
		}
		
		private function findEvent(evtType:String, listener:Function):int
		{
			var arrEvent:Array = _event[evtType];
			var ind:int = -1;
			for (var i:int = 0; i < arrEvent.length; i++)
			{
				if (arrEvent[i] === listener) {
					return i;
				}
			}
			return ind;
		}
		
		public function hasEventListener(evtType:String):Boolean 
		{
			return !!_event[evtType];
		}
		
		public function removeEventListener(evtType:String, listener:Function=null):void 
		{
			if (!listener)
				_event[evtType] = [];
			else
			{
				var ind:int = findEvent(evtType, listener);
				if (ind != -1)
					_event[evtType].splice(ind, 1);
			}
		}
		
		public function dispatchEvent(event_:BasicEvent):Boolean 
		{
			var arrEvent:Array = this._event[event_.type];
			if(!arrEvent)
				return;
			//TODO Try catch, ne fonctione pas sous opera
			if(!event_.currentTarget)
				event_.currentTarget = this;
			for (var i = 0; i < arrEvent.length; i++)
			{
				arrEvent[i](event_);
				if (event_.skip)
					break;
			}
		}
		
	
		
	}

}